<template>
  <div style="border: 1px solid #ccc">
    <Toolbar :defaultConfig="toolbarConfig" :editor="editorRef" :mode="mode" style="border-bottom: 1px solid #ccc"/>
    <Editor v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode"
            style="height: 450px; overflow-y: hidden;"
            @onChange="contentChange" @onCreated="handleCreated"/>
  </div>
</template>

<script lang="ts" setup>
// 引入 css  可以在main.js中引入
import '@wangeditor/editor/dist/css/style.css'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'

const editorRef = shallowRef()
const valueHtml = ref('<p>hello</p>')
const mode = 'default'
const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      async customUpload(file: any, insertFn: any) {
        const fileBase64 = fileToBase64Async(file)
        insertFn(fileBase64)
      }
    }
  }
}

/**
 * file 转base64 DataURL
 * @param file
 */
function fileToBase64Async(file) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (e) => {
      resolve(e.target.result);
    };
  });
}

const props = defineProps({})
const emits = defineEmits(["contentChange"])

// 模拟 ajax 异步获取内容
// onMounted(() => {
//   setTimeout(() => {
//     valueHtml.value = props.text ?? "" //回显数据
//     // const toolbar = DomEditor.getToolbar(editorRef.value) as any;
//     // const curToolbarConfig = toolbar.getConfig();
//     // console.log(curToolbarConfig.toolbarKeys);  //这里会打印出所有的key
//   }, 1500)
// })

function setValueHtml(html: string) {
  setTimeout(() => {
    valueHtml.value = html
  })
}
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null)
    // 销毁 editor 实例
    return editor.destroy()
})

// 返回html内容给外部
function contentChange() {
  emits("contentChange", valueHtml.value)
  return valueHtml.value
}

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

defineExpose({
  contentChange,
  setValueHtml
})
</script>

<style lang="scss" scoped>
.editor {
  width: 100%;
  // 修改工具栏的背景色

  .w-e-bar {
    background: var(--w-e-bar-bg-color);

  }
}

// 去除内置样式
.w-e-text-container blockquote, .w-e-text-container li,
.w-e-text-container p,
.w-e-text-container td,
.w-e-text-container th,
.w-e-toolbar * {
  line-height: unset !important;

}
</style>
